<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
  <div class="user">
    <basic-container>

      <avue-crud
              v-model:search="form"
              v-model:page="page"
              :permission="getPermission"
              v-bind="bindVal"
              v-on="onEvent"
              :option="option"
              :data="tableData"
              :span-method="spanMethod"
              :before-open="beforeOpen"
      >
        <template #menu="scope">

            <el-button link type="primary" v-if="!showDetailBtn" v-for="(item, index) in tableRowBtns" @click="doRowBtn(item,scope.row)">{{item.name}}</el-button>

            <el-button link type="primary"  icon="el-icon-edit" v-if="showDetailBtn" @click="openDetail(scope.row, scope.index)">详情</el-button>

            <el-button link type="primary"  icon="el-icon-edit" v-if="!showDetailBtn && showFormBtn&&queryFormData.app && queryFormData.app.formId" @click="showFormHandle(scope.row, scope.index)">编辑</el-button>
        </template>

        <template #menu-left="{size}">
           <el-button type="primary" v-if=" showFormBtn&&queryFormData.app && queryFormData.app.formId" @click="showFormHandle()">新增</el-button>
          <el-button type="primary" v-if="option.importAddBtn" @click="importShowHandle('insert')">新增导入</el-button>
          <el-button type="primary" v-if="option.importEidtBtn"   @click="importShowHandle('update')">修改导入</el-button>
          <el-button type="primary" v-if="option.exportBtn"  @click="exportHandle()">导出</el-button>
          <el-button type="primary" v-if="!showDetailBtn"  v-for="(item, index) in tableHeaderBtns"  @click="doTableBtn(item)">{{item.name}}</el-button>

        </template>

        <template #header v-if="groupOptionsVisible && groupOptionsVisibleMobile">
          <avue-form :option="groupOptions" v-model="mysearch"   ></avue-form>
        </template>
      </avue-crud>


    </basic-container>

      <div style="text-align: center;width: 100%"  v-if="showEchat">
           <el-radio-group v-model="echatType" size="small" >
             <el-radio label="ec1">折线图</el-radio>
             <el-radio label="ec2" >柱状图</el-radio>
           </el-radio-group>
          <div class="threeBarChart" id="echartsId"  ref="echartsId" :width="widthChart"  style="text-align:center;width:100%;height:300px"></div>
      </div>


      <div>
          <el-dialog title="详情" v-model="detailVisible"  style="width: 80vw;height: 80vh;border: 0px" append-to-body>
                <iframe  style="width: 75vw;height: 70vh;border: 0px" :src="detailUrl"></iframe>
          </el-dialog>
      </div>


      <div>
          <el-dialog :title="openwin.title" v-model="openwin.show"  :width="openwin.width"  append-to-body>
              <iframe id="bdIframe"  style="width:100%;height: 70vh;border: 0px" :src="openwin.url" scrolling="yes"></iframe>
          </el-dialog>
      </div>


    <import-upload :base-url="pageConfig.url" :absolute-url="pageConfig.absoluteUrl" :model-name="pageConfig.name" v-model="importDialogVisible" :params="pageConfig.params"></import-upload>

  </div>


</template>
<script>
  import {pageCore,listCore,delCore,getCore,saveCore,importCore,exportCore,downloadCore} from "@/framework-core/api/core/api";
  import {queryByApp} from "@/framework-admin/api/code/formquery";
  import request from '@/framework-core/axios';
  import website from '@/framework-core/config/website';
  import { convertHtmlByParam,convertVantMobile,removeEmptyFields,loadEChartsScript} from '@/framework-core/utils/util'
  // import * as echarts from 'echarts'
  import {getFormModel} from "@/framework-admin/api/code/formmodel";
  import ImportUpload from "@/framework-core/components/upload/index.vue";


  export default {
    name: "formq",
    components: {ImportUpload},
      data() {
          return {
              def:{
                  isGroup:false,//是否分组
                  groupIndexes:[],
                  tjIndexes:[]
              },
              sumColumnList:[],
              importDialogVisible:false,
              frame:false,
              rangList:[],
              appCode: "",
              importType: "",
              djson:"",// 参数
              tableSearchVisible: false,
              tableHeaderBtns:[],
              tableRowBtns:[],
              showDetailBtn: false,
              showFormBtn:false,
              detailVisible: false,
              tableData: [],
              pageConfig: {"url": "/form/tableData",absoluteUrl: website.baseUrl+"/api/form/tableData/download2?type=1",name:"导入",params: {"":""}},
              loading: false,
              form: {},
              sysParamForm:{},
              mysearch: {},
              option: {},
              spanArr:[],// 合拼单元格 [{prop: 'name'}]
              tableDicMap:{},
              groupOptionsVisible: false,
              groupOptionsVisibleMobile:true,
              groupOptions: {column: [], submitBtn: false, menuBtn: false},
              groupTitleMap:{},
              imgdatas: [],
              queryFormData: {},
              sortData: {
                  sort: "", order: ""
              },
              openwin:{
                  show:false,
                  title:"",
                  width:'100%',
                  height:'100%',
                  url:''
              },
            echatType:"ec2",
            echatTypes:{
                "ec1":{"xAxisType":"category","seriesType":"line","seriesStack":"Total"},
                "ec2":{"xAxisType":"","seriesType":"bar","seriesStack":"x"},
            },
              echatOption: {
                  title: {text: '统计表'},
                  grid: {
                      left: "1%",
                      right: "2%",
                      bottom: "3%",
                      with: '100%',
                      containLabel: true,
                  },
                  // echart工具箱
                  tooltip: {
                      trigger: 'axis',
                      // 点击条形图展示具体数据
                      formatter(params) {
                          return params[0].name + ":" + params[0].data;
                      }
                  },
                  xAxis: {},
                  yAxis: {type: 'value'},
                  series: []
              },
              myecharts: "",
              widthChart: "80%",
              heightChart:"1px",
              showEchat: true,
              page: {
                  total: 0, // 总页数
                  currentPage: 1, // 当前页数
                  pageSize: 20 // 每页显示多少条
              },
          };
      },
    computed: {
      ...mapState({
        permissions: (state) =>state.user.permission,
      }),
      bindVal() {
        return {
          ref: 'crud'
        }
      },
      onEvent() {
        return {
          // 'on-load': this.getPage,
          'row-save': this.handleInsert,
          'row-update': this.handleUpdate,
          'row-del': this.handleDel,
          'refresh-change': this.refreshChange,
          'search-reset': this.searchChange,
          'search-change': this.searchChange,
          'current-change': this.currentChange,
          'sort-change':this.sortChange
        }
      },
      onEventSort() {
        return {
          'sort-change':this.sortChange
        }
      },
      rowKey() {
        return this.config.rowKey || 'id'
      }

    },
    created() {
        if(window.isMobile){
            this.page.layout = "total,prev, next";
        }
        this.init();
        this.getFormJson();

    },
      watch: {
          'mysearch.groups.length': function(newLength, oldLength) {
              this.showEchat = newLength>0;
          },
          'echatType': function(newLength, oldLength) {
            //alert(newLength)
            this.drawEcharts(this.tableData);
        }
      },

      mounted() {
          loadEChartsScript();
          setTimeout(() => {
            if(echarts){
              this.myecharts = echarts.init(this.$refs.echartsId);
              this.drawEcharts();
            }
          }, 3000)

          // window.addEventListener('resize', this.resizeChart)
      },
    methods: {
      init() {
        this.detailUrl = location.href;
        this.djson = this.$route.query.djson;
        this.frame = this.$route.query.frame || false;
        this.def.isGroup = this.$route.query.isGroup || false;
        if (this.$route.query.groupIndexes) {
          this.def.groupIndexes = this.$route.query.groupIndexes.split(",");
        } else {
          this.def.groupIndexes = [];
        }
        if (this.$route.query.tjIndexes) {
          this.def.tjIndexes = this.$route.query.tjIndexes.split(",");
        } else {
          this.def.tjIndexes = [];
        }

        if (this.djson) {
          var jsonStrDecoded = JSON.parse(decodeURIComponent(this.djson));
          for (const key in jsonStrDecoded) {
            if (jsonStrDecoded.hasOwnProperty(key)) {
              this.form[key] = jsonStrDecoded[key];
            }
          }
        }

        Object.keys(this.$route.query).forEach((key) => {
          this.form[key] = this.$route.query[key];
        });

      },
      // resizeChart() {
      //     if (this.$refs.echartsId) {
      //         this.$refs.echartsId.resize()
      //        // console.log('1111')
      //     }
      // },
      drawEcharts(data) {
        //this.myecharts.setOption( this.echatOption);

        if (!this.mysearch.groups || this.mysearch.groups.length < 1 || !this.mysearch.txs || this.mysearch.txs.length < 1) {
          this.showEchat = false;
          return
        }
        this.widthChart = "100%";
        this.heightChart = "300px";
        this.showEchat = true;
        let xAxis = {};
        xAxis.type = this.echatTypes[this.echatType].xAxisType;
        if (!xAxis.type) {
          delete xAxis.type
        }
        xAxis.data = [];
        let series = [];
        let legend = {};
        legend.data = [];
        legend.data2 = [];
        let seriesMap = {};

        for (let xindex = 0; xindex < this.mysearch.txs.length; xindex++) {
          let p = this.mysearch.txs[xindex];
          legend.data.push(this.groupTitleMap[p]);
          legend.data2.push(p);
          let m = {}
          m.name = this.groupTitleMap[p]
          m.type = this.echatTypes[this.echatType].seriesType
          m.stack = this.echatTypes[this.echatType].seriesStack
          m.data = [];
          series.push(m);
          seriesMap[m.name] = m;
        }


        for (let dindex = 0; dindex < data.length; dindex++) {
          let d = data[dindex];
          let xdata = "";
          for (let xindex = 0; xindex < this.mysearch.groups.length; xindex++) {
            let p = this.mysearch.groups[xindex];

            let titleTemp = this.tableDicMap[p] ? (this.tableDicMap[p][d[p]] || "") : "";
            xdata += xdata ? ("," + titleTemp) : titleTemp;
          }
          xAxis.data.push(xdata)

          for (let xindex = 0; xindex < legend.data2.length; xindex++) {
            let p = legend.data2[xindex];

            let m = seriesMap[this.groupTitleMap[p]]
            m.data.push(d[p] || 0);
          }
        }

        let myecharts = echarts.init(this.$refs.echartsId);
        // 绘制图表
        this.echatOption.xAxis = xAxis;
        this.echatOption.series = series;
        this.echatOption.legend = legend;
        // alert(JSON.stringify(series))

        myecharts.setOption(this.echatOption);


      },
      getFormJson() {
        this.appCode = this.$route.query.app;
        this.pageConfig.params = {};
        this.pageConfig.params.app = this.appCode;
        this.option = {
          "border": true,
          "index": true,
          "indexLabel": "#",
          "stripe": true,
          "menuAlign": "center",
          "align": "center",
          searchLabelWidth: 150,
          editBtn: false,
          saveBtn: true,
          addBtn: false,
          delBtn: false,
          "searchMenuSpan": 6,
          grid: window.isMobile,
          gridSpan: 24,
          "column": []
        };
        this.groupOptionsVisible = false;
        queryByApp({"app": this.appCode}).then(response => {

          this.queryFormData = response.data.data;
          this.initBtn();

          // 系统参数
          if (this.queryFormData.param) {
            for (let indexa = 0; indexa < this.queryFormData.param.length; indexa++) {
              var paramTemp = this.queryFormData.param[indexa];
              this.sysParamForm[paramTemp.pkey] = paramTemp.pvalue;
            }
          }


          let mapCols = {};
          if (this.queryFormData.form) {
            let optionForm = eval("(" + this.queryFormData.form.modelJson + ")") || {};
            optionForm.column.forEach((column) => {
              mapCols[column.prop] = column;
            });
            if (optionForm.group) {
              optionForm.group.forEach((groupItem) => {
                if (groupItem.column) {
                  groupItem.column.forEach((column22) => {
                    mapCols[column22.prop] = column22;
                  });
                }
              });
            }
          }

          if (this.queryFormData.models) {
            let selectcolumns = [];
            let groupDics = [];
            let txDics = [];
            let selectcolumnsGroup = [];
            for (let indexf = 0; indexf < this.queryFormData.models.length; indexf++) {
              let fied = this.queryFormData.models[indexf];

              if (!!fied.isQuery) {
                let selectcolumn = {
                  "type": fied.columnShowType || "input",
                  "label": fied.label,
                  "labelWidth": 120,
                  "prop": fied.prop,
                  'search': !!fied.queryType && fied.queryType != "range",
                  "span": 12
                }

                if ("id" == selectcolumn.prop) {
                  selectcolumn.hide = true;
                  selectcolumn.display = false;
                  selectcolumn.overHidden= true;
                }
                if ("creater" == selectcolumn.prop) {
                  //selectcolumn.display = false;
                  selectcolumn.formatter = (val, value, label) => { return val.createrName; }
                }
                if ("updater" == selectcolumn.prop) {
                  //selectcolumn.display = false;
                  selectcolumn.formatter = (val, value, label) => { return val.updaterName; }
                }
                if(fied.columnWidth){
                  selectcolumn.width = fied.columnWidth
                  if(fied.columnWidth<=1){

                    selectcolumn.display = false;
                    selectcolumn.hide= true;
                  }
                }
                switch (selectcolumn.type) {
                  case "input":
                    break;
                  case "rule":
                    selectcolumn.type = "input";
                    if(fied.showRuleFun){
                      selectcolumn.formatter = eval(fied.showRuleFun)
                    }
                    break;
                  case "number":

                    break;
                  case "select":
                    //selectcolumn.dicData = this.$dictObject[fied.dicValue];

                    if (this.queryFormData.dics && fied.dicValue) {
                      selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    }
                    break;
                  case "radio":
                    selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    break;
                  case "checkbox":
                    selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    break;
                  case "switch":
                    selectcolumn.dicData = [{"label": "否", "value": 0}, {"label": "是", "value": 1}];
                    break;
                  case "date":
                    selectcolumn.format = 'YYYY年MM月DD日';
                    break;
                  case "datetime":
                    selectcolumn.format = 'YYYY年MM月DD日 hh:mm';
                    break;
                  case "year":
                    selectcolumn.format = 'YYYY年';
                    break;
                  case "week":
                    selectcolumn.dateformat = "week";
                    //selectcolumn.type=  "input",
                    break;
                  case "month":
                    selectcolumn.format = 'YYYY年MM月';
                    break;
                  case "time":
                    selectcolumn.format = 'hh:mm';
                    break;
                  case "cascader":
                    break;
                  case "userChoose":
                    selectcolumn.type = 'userChoose';
                    selectcolumn.component = 'userChoose';
                    break;
                  case "orgTreeChoose":
                    selectcolumn.type = 'orgTreeChoose';
                    selectcolumn.component = 'orgTreeChoose';
                    break;
                  case "roleTreeChoose":
                    selectcolumn.type = 'roleTreeChoose';
                    selectcolumn.component = 'roleTreeChoose';
                    break;
                  case "upload":
                    selectcolumn.type = "upload";
                    selectcolumn.listType = "picture-img";
                    selectcolumn.addDisplay = false;
                    selectcolumn.editDisplay = false;
                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                    break;
                  case "ueditor":
                    selectcolumn.type = "ueditor";
                    selectcolumn.overHidden = true;
                    selectcolumn.component = "avueUeditor";
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";

                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                    selectcolumn.propsHttp = {
                      // 上传完成返回的json的root
                      "res": "data.data",
                      // 上传完成返回的图片路径
                      "url": "url",
                      // 上传文件名，默认file
                      "fileName": "file",
                    };
                    selectcolumn.search = false;
                    selectcolumn.span = 24
                    break;
                }

                let formColumn = mapCols[fied.prop];
                if (formColumn) {
                  if (formColumn.dicData && !selectcolumn.dicData) {
                    selectcolumn.dicData = formColumn.dicData;
                  }
                }


                if (fied.tag) {
                  if (fied.tag.indexOf("overHidden") >= 0) {
                    selectcolumn.overHidden = true;
                  }
                  if (fied.tag.indexOf("fixed") >= 0) {
                    selectcolumn.fixed = true;
                  }
                  if (fied.tag.indexOf("showSummary_") >= 0) {
                    if (fied.tag.indexOf("showSummary_avg") >= 0) {
                      this.sumColumnList.push( { name: fied.prop, type: 'avg' })
                    }else if (fied.tag.indexOf("showSummary_count") >= 0) {
                      this.sumColumnList.push( { name: fied.prop, type: 'count' })
                    }else if (fied.tag.indexOf("showSummary_sum") >= 0) {
                      this.sumColumnList.push( { name: fied.prop, type: 'sum' })
                    }

                  }
                  if (fied.tag.indexOf("merge") >= 0) {
                    this.spanArr.push({
                      prop: fied.prop, span: []
                    })
                  }
                }

                selectcolumns.push(selectcolumn);

                if (selectcolumn.dicData) {
                  this.tableDicMap[fied.prop] = {};
                  for (let ind = 0; ind < selectcolumn.dicData.length; ind++) {
                    this.tableDicMap[fied.prop][selectcolumn.dicData[ind].value] = selectcolumn.dicData[ind].label;
                  }
                }

                this.addRangSearch(selectcolumns, fied, selectcolumn);
                if (selectcolumn.type == "upload") {
                  var othercolumn = {
                    "type": "upload",
                    "label": fied.label,
                    "prop": fied.prop,
                    "overHidden": false,
                    hide: true,
                    imgUploadColumn: true,
                    listType: 'picture-img',
                    propsHttp: {
                      url: 'url',
                      name: 'name',
                      res: 'data.data'
                    },
                    limit: 1,
                    loadText: '图片上传中，请稍等',
                    canvasOption: {
                      text: "",
                      ratio: 0.1,
                    },
                    accept: 'image/png, image/jpeg',
                    cropperOption: {
                      autoCropWidth: 100,
                      autoCropHeight: 100,
                      fixed: true,
                      fixedNumber: [100, 100],
                    },
                    tip: '只能上传jpg/png文件，且不超过500kb',
                    action: website.baseUrl + "/api/sys/file/upload",
                    "rules": [{
                      required: false,
                      message: fied.label + '不能为空',
                      trigger: 'blur'
                    }],
                    'search': false,
                    "span": 24
                  }
                  selectcolumns.push(othercolumn);
                }
              }
              if (!!fied.isGroup) {
                var gcolumn = {"label": fied.label, "value": fied.prop}
                groupDics.push(gcolumn);
              }
              if (!!fied.groupType) {

                let groupTypeTemps = fied.groupType.split(",");
                let groupJson = eval('(' + fied.groupJson + ')') || {};
                for (let indexG = 0; indexG < groupTypeTemps.length; indexG++) {
                  let groupTypes = "";
                  switch (groupTypeTemps[indexG]) {
                    case "avg" :
                      groupTypes = "平均值";
                      break;
                    case "max" :
                      groupTypes = "最大值";
                      break;
                    case "min" :
                      groupTypes = "最小值";
                      break;
                    case "sum" :
                      groupTypes = "求和";
                      break;
                    case "count" :
                      groupTypes = "个数";
                      break;
                    case "other" :
                      groupTypes = "其他";
                      break;
                  }
                  let txcolumn = {
                    "label": fied.label + groupTypes,
                    "value": groupTypeTemps[indexG] + "_" + fied.prop
                  }
                  let asTitle = groupJson[groupTypes];
                  txcolumn.label = asTitle || (fied.label + groupTypes);
                  this.groupTitleMap[txcolumn.value] = txcolumn.label;
                  txDics.push(txcolumn);

                  let selectcolumn = {
                    "type": "input",
                    "label": txcolumn.label,
                    "prop": groupTypeTemps[indexG] + "_" + fied.prop,
                    'mgroup': true,
                    hide: true,
                    display: false,
                    'search': false,
                    "span": 12
                  }
                  selectcolumnsGroup.push(selectcolumn);
                }
              }

            }

            // 将统计字段放在最后
            if (selectcolumnsGroup.length > 0) {
              selectcolumns = selectcolumns.concat(selectcolumnsGroup);
              // for(let indexa=0;indexa<selectcolumnsGroup.length;indexa++){
              //     selectcolumns.push(selectcolumnsGroup[indexa]);
              // }

            }
            if(this.sumColumnList.length>0){
              this.option.sumColumnList = this.sumColumnList;
              this.option.showSummary = true;
            }
            this.option.column = selectcolumns;
            this.option.selection = true;
            if (groupDics && groupDics.length > 0) {
              this.groupOptions.column[0] = {label: '分组字段', prop: 'groups', type: 'checkbox'}
              this.groupOptions.column[0].dicData = groupDics;
              this.groupOptions.column[1] = {label: '统计字段', prop: 'txs', type: 'checkbox'}
              this.groupOptions.column[1].dicData = txDics;
              this.groupOptionsVisible = true && !this.djson;

              if (this.def.isGroup) {
                this.groupOptionsVisibleMobile = false;
                this.mysearch = {};
                this.mysearch.groups = [];
                this.mysearch.txs = [];
                if (this.groupOptions.column[0].dicData && this.groupOptions.column[1].dicData) {
                  // alert(JSON.stringify(this.def.groupIndexes))
                  if (this.def.groupIndexes && this.def.groupIndexes.length >= 0) {
                    for (let aindex = 0; aindex < this.groupOptions.column[0].dicData.length; aindex++) {
                      if (this.def.groupIndexes.indexOf((aindex + 1) + "") >= 0) {
                        let gdata = this.groupOptions.column[0].dicData[aindex];
                        if (gdata) {
                          this.mysearch.groups.push(gdata.value);
                        }
                      }
                    }
                  } else {
                    for (let aindex = 0; aindex < this.groupOptions.column[0].dicData.length; aindex++) {
                      let gdata = this.groupOptions.column[0].dicData[aindex];
                      if (gdata) {
                        this.mysearch.groups.push(gdata.value);
                      }
                    }
                  }

                  if (this.def.tjIndexes && this.def.tjIndexes.length > 0) {
                    for (let aindex = 0; aindex < this.groupOptions.column[1].dicData.length; aindex++) {
                      if (this.def.tjIndexes.indexOf((aindex + 1) + "") >= 0) {
                        let gdata = this.groupOptions.column[1].dicData[aindex];
                        if (gdata) {
                          this.mysearch.txs.push(gdata.value);
                        }
                      }
                    }
                  } else {
                    for (let aindex = 0; aindex < this.groupOptions.column[1].dicData.length; aindex++) {
                      let gdata = this.groupOptions.column[1].dicData[aindex];
                      if (gdata) {
                        this.mysearch.txs.push(gdata.value);
                      }
                    }
                  }
                }


              }
              convertVantMobile(this.groupOptions, false);
            }


            convertVantMobile(this.option, false);

          }


          this.option.menu = (this.tableRowBtns.length + (this.showDetailBtn ? 1 : 0) + ((this.showFormBtn && this.queryFormData.app && this.queryFormData.app.formId) ? 1 : 0)) > 0;

          this.getPage();
        });

      },

      addRangSearch(selectcolumns, fied, selectcolumn) {
        if (fied.queryType != "range") {
          return
        }
        let selectcolumnStar = {
          "type": selectcolumn.type,
          "label": "开始" + selectcolumn.label,
          "prop": selectcolumn.prop + "Star",
          'search': true,
          "labelWidth": 120,
          "hide": true,
          "span": 12
        }
        if (selectcolumn.dicData) {
          selectcolumnStar.dicData = selectcolumn.dicData;
        }
        if (selectcolumnStar.dicCode) {
          selectcolumnStar.dicCode = selectcolumn.dicCode;
        }
        if (selectcolumnStar.format) {
          selectcolumnStar.format = selectcolumn.format;
        }
        selectcolumns.push(selectcolumnStar);

        let selectcolumnEnd = {
          "type": selectcolumn.type,
          "label": "结束" + selectcolumn.label,
          "prop": selectcolumn.prop + "End",
          'search': true,
          "labelWidth": 120,
          "hide": true,
          "span": 12
        }
        if (selectcolumnEnd.dicData) {
          selectcolumnEnd.dicData = selectcolumn.dicData;
        }
        if (selectcolumnEnd.dicCode) {
          selectcolumnEnd.dicCode = selectcolumn.dicCode;
        }
        if (selectcolumnEnd.format) {
          selectcolumnEnd.format = selectcolumn.format;
        }
        selectcolumns.push(selectcolumnEnd);
        this.rangList.push(selectcolumn.prop + "Star");
        this.rangList.push(selectcolumn.prop + "End");


      },

      initBtn() {
        this.option.menu = false;
        this.tableRowBtns = [];
        this.tableHeaderBtns = [];
        if (!this.queryFormData.operate) {
          return
        }
        for (var i = 0; i < this.queryFormData.operate.length; i++) {
          var btnTemp = this.queryFormData.operate[i];
          switch (btnTemp.btnType) {
            case 1:
              //表头
              this.tableHeaderBtns.push(btnTemp);
              break;
            case 2:
              //行内
              this.tableRowBtns.push(btnTemp);
              break;
            case 3:
              //表单
              break;
            case 4:
              //新增
              if (this.queryFormData.app.formId) {
                this.showFormBtn = true;
              } else {
                this.option.addBtn = true;
              }

              break;
            case 5:
              //修改
              if (this.queryFormData.app.formId) {
                this.showFormBtn = true;
              } else {
                this.option.editBtn = true;
              }
              this.option.menu = true;
              break;
            case 6:
              //删除
              this.option.delBtn = true;
              this.option.menu = true;
              break;
            case 7:

              //新增导入
              this.option.importAddBtn = true;
              break;
            case 8:
              //修改导入
              this.option.importEidtBtn = true;
              break;
            case 9:
              //导出
              this.option.exportBtn = true;
              break;

            case 10:
              //预览
              this.option.previewBtn = true;
              this.option.menu = true;
              break;

          }

        }

      },

      doRowBtn: function (btn, row) {
        const contentClick = convertHtmlByParam(btn.contentClick, row, this.$route.query, this.sysParamForm);
        switch (btn.onClick) {
          case 1:
            window.open(contentClick, '_blank');
            break;
          case 2:
            window.open(contentClick, '_self');
            break;
          case 3:
            this.openwin.url = contentClick;
            this.openWindHander(btn);
            break;
          case 4:
            this.clickSelfJs(contentClick,this.row)
            break;
          case 5:
            window.open(contentClick, '_blank');
            break;
        }
      },
      clickSelfJs:function (js,data) {
        let seflBut = eval(js);
        seflBut(this,data)
      },
      doTableBtn: function (btn) {
        const contentClick = convertHtmlByParam(btn.contentClick, {}, this.$route.query, this.sysParamForm);
        switch (btn.onClick) {
          case 1:
            window.open(contentClick, '_blank');
            break;
          case 2:
            window.open(contentClick, '_self');
            break;
          case 3:
            this.openwin.url = contentClick;
            this.openWindHander(btn);
            break;
          case 4:
            this.clickSelfJs(contentClick,this.tableData)
            //window.open(contentClick, '_blank');
            break;
          case 5:
            window.open(contentClick, '_blank');
            break;
        }
      },

      openWindHander(btn) {
        this.openwin.title = btn.name || '窗口';
        this.openwin.width = btn.width || '100%';
        this.openwin.height = btn.height || '100%';
        this.openwin.show = true;
        setTimeout(function () {

          /**
           * iframe-宽高自适应显示
           */
          const oIframe = document.getElementById("bdIframe");
          const deviceWidth = document.documentElement.clientWidth;
          const deviceHeight = document.documentElement.clientHeight;
          // oIframe.style.width = Number(deviceWidth) - 220 + "px"; //数字是页面布局宽度差值
          oIframe.style.width = Number(deviceWidth); //数字是页面布局宽度差值
          oIframe.style.height = Number(deviceHeight) - 120 + "px"; //数字是页面布局高度差
        }, 1000);
      },


      getPermission: function (key, row, index) {
        //return this.getCommPermission(key, row, index);
        return true;
      },

      getPage() {
        this.showDetailBtn = false;

        if (!this.checkGroup()) {
          return;
        }
        this.loading = true;
        if (window.isMobile) {
          this.option.grid = false;
        }
        let paramsData = this.buildParam();
        let bntNum = this.tableRowBtns.length + (this.showDetailBtn ? 1 : 0) + ((this.showFormBtn && this.queryFormData.app && this.queryFormData.app.formId) ? 1 : 0);
        this.option.menu = bntNum > 0;
        this.initBtn();
        return request({
          url: website.baseUrl + '/api/' + this.pageConfig.url + '/page',
          method: 'post',
          data: paramsData,
          params: {"app": this.appCode}
        }).then(response => {

          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.loading = false;
          if (window.isMobile) {
            this.option.grid = window.isMobile;
          }
          this.rowSort()
          this.rowCalc();
          this.drawEcharts(this.tableData);
        })
            .catch(() => {
              this.loading = false;
            });
      },
      handleInsert: function (row, done, loading) {

        saveCore("/form/tableData", row, {"app": this.appCode}).then(() => {
          this.getPage(this.page);
          this.$message.success("创建成功");
          if (done) {
            done();
          }
        }).catch(() => {
          if (loading) {
            loading();
          }
        });
        ;
      },
      handleUpdate: function (row, index, done, loading) {
        saveCore("/form/tableData", row, {"app": this.appCode}).then(() => {
          this.getPage(this.page);
          this.$message.success("修改成功");
          done();
        });
      },
      handleDel: function (row, index) {
        let $that = this;
        this.$confirm("是否确认删除：" + ("序号" + (index + 1)), "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
            .then(function () {
              return delCore("/form/tableData", row, {"app": $that.appCode});
            })
            .then(() => {
              this.getPage(this.page);
              this.$message.success("删除成功");
            });
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
        this.page.currentPage = 1
        this.getPage(this.page);
      },
      currentChange(current) {
        this.page.currentPage = current;
        this.getPage(this.page);
      },
      refreshChange() {
        this.getPage(this.page);

      },
      searchChange(form, done) {
        this.page.currentPage = 1;
        this.getPage(this.page, form);

        done();
      },
      sortChange(column, prop, order) {

        this.sortData.sort = column.prop;
        this.sortData.order = column.order;
        this.getPage(this.page);
        // this.$message.success( this.sortData.prop+ this.sortData.order);
      },
      beforeOpen(show, type) {
        if (type == "edit") {
        }
        show();
      },
      checkGroup() {

        if ((!!this.mysearch.groups && this.mysearch.groups.length > 0) && (!this.mysearch.txs || this.mysearch.txs.length == 0)) {
          this.$message({
            message: "请选择统计类型",
            type: 'error'
          })
          return false;
        }
        if ((!!this.mysearch.txs && this.mysearch.txs.length > 0) && (!this.mysearch.groups || this.mysearch.groups.length == 0)) {
          this.$message({
            message: "请选择分组类型",
            type: 'error'
          })
          return false;
        }
        this.showSelectColumn();
        return true;
      },
      showSelectColumn() {

        let cols = [];
        let isgroup = false;
        if ((!!this.mysearch.txs && this.mysearch.txs.length > 0) && (!!this.mysearch.groups && this.mysearch.groups.length > 0)) {
          this.mysearch.groups.forEach(function (element) {
            cols.push(element)
          });
          this.mysearch.txs.forEach(function (element) {
            cols.push(element)
          });
          isgroup = true;
        }

        debugger
        let rangList = this.rangList;
        this.option.column.forEach(function (col) {
          if (isgroup) {
            col.hide = !cols.includes(col.prop);
          } else {
            col.hide = col.mgroup || rangList.includes(col.prop) || "id" == col.prop || false;
          }
          if (col.imgUploadColumn) {
            col.hide = true;
          }
          if(col.width<=1){
            col.hide = true;
          }
        });
      },

      buildParam() {
        // var xm = this.form.xm;
        //this.$message.success(JSON.stringify( this.form));
        var entity = Object.assign(
            {},
            {},
            this.form
        );
        var obj = {
          pageNum: this.page.currentPage,
          pageSize: this.page.pageSize,
        };
        obj.entity = removeEmptyFields(entity);
        if (this.groupOptionsVisible) {
          obj.entity.group = true;
          this.showDetailBtn = true;
          this.option.delBtn = false;
          if (this.mysearch.groups && this.mysearch.groups.length > 0) {
            obj.entity.groupStr = this.mysearch.groups.join(',');

            if (this.mysearch.txs && this.mysearch.txs.length > 0) {
              obj.entity.txsStr = this.mysearch.txs.join(',');
            }
          }
        }

        if (this.sortData.sort) {
          obj.sort = this.sortData.sort
          obj.order = (this.sortData.order || "dascending") == "dascending" ? "desc" : "asc";
        }
        return obj;
      },
      importShowHandle(type) {
        this.importDialogVisible = true;
        this.importType = type;
      },
      upAndDowndoad(params) {
        let form = new FormData()
        form.append('file', params.file)
        importCore(
            this.pageConfig.url,
            form,
            {"app": this.appCode, "importType": this.importType}
        ).then(response => {
          this.getPage(this.page);
          this.$message.success("导入成功");
          this.loading = false;
        })
            .catch((data) => {
              if (data.state = 200) {
                this.getPage(this.page);
                this.$message.success("导入成功");
                this.loading = false;
              }
              if (data.state = -99) {
                if (data.data) {
                  if (data.data.url) {
                    this.$confirm("导入失败：" + data.message + ',请下载文件查看详情 ?', '提示', {
                      confirmButtonText: '下载',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                      this.downFile(data.data.url);
                    }).catch(() => {
                    })
                  } else if (data.data.uuid) {
                    this.$message({
                      message: "导入失败：" + data.message,
                      type: 'error'
                    })
                  } else {
                    this.$message({
                      message: "导入失败：" + data.message,
                      type: 'error'
                    })
                  }
                } else {
                  this.$message({
                    message: "导入失败：" + data.message,
                    type: 'error'
                  })
                }
              }
              this.loading = false;
            });
      },

      exportHandle() {
        let entity = this.buildParam();
        entity.exportMap = {};
        if (this.option.column) {
          for (let indexk = 0; indexk < this.option.column.length; indexk++) {
            let column = this.option.column[indexk];
            if (!column.hide) {
              entity.exportMap[column.prop] = column.label
            }
          }
        }

        exportCore(this.pageConfig.url, entity, {
          "app": this.appCode,
          "importType": this.importType
        }).then((response) => {
          this.downFile(response.data.data.url, response.data.data.tag);
          this.$message.success("导出成功");
          done();
        });
      },

      downExcel() {
        var url = downloadCore(this.pageConfig.url);
        this.downFile(url + "?fileName=" + encodeURIComponent(this.uploadCpnfig.file), this.uploadCpnfig.file);
      },
      showFormHandle(row) {
        let routerJump = this.$router.resolve({
          path: "/form/preview?formId=" + this.queryFormData.app.formId,
          query: {formId: this.queryFormData.app.formId}
        });
        this.openwin.title = row ? "编辑" : "新增";
        this.openwin.width = '80%';
        this.openwin.height = '50vh';
        this.openwin.url = routerJump.href + (row ? "&dataId=" + row.id : "");
        this.openwin.show = true;
      },

      openDetail(row) {
        this.detailUrl = location.href;
        if (this.detailUrl.indexOf("?") <= 0) {
          this.detailUrl += "?frame=1"
        } else {
          this.detailUrl += "&frame=1"
        }
        var djson = {};
        for (var xindex = 0; xindex < this.mysearch.groups.length; xindex++) {
          var detailp = this.mysearch.groups[xindex];
          var detailv = row[detailp];
          djson[detailp] = detailv;
          //this.detailUrl += "&" + detailp + "=" + detailv;
        }
        var jsonStr = JSON.stringify(djson);

        var urlEncodedJsonStr = encodeURIComponent(jsonStr);

        this.detailUrl += "&djson=" + urlEncodedJsonStr;
        this.detailVisible = true;
      },
      rowCalc() {
        this.spanArr.forEach((ele, index) => {
          let parent
          if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span
          ele.span = this.rowSpan(ele.prop, parent)
        })
      },
      rowSort() {
        let propList = this.spanArr.map(ele => ele.prop);
        this.spanArr.forEach((ele, index) => {
          let key = ele.prop;
          this.tableData =  this.tableData.sort((a, b) => {
            let flag = true;
            for (let i = 0; i < index; i++) {
              let prop = this.spanArr[i].prop;
              flag = flag && a[prop] == b[prop];
            }
            if (flag) {
              if (a[key] < b[key]) { return 1; }
              else if (a[key] > b[key]) { return -1; }
              return 0;
            }
            return 0;
          });
        });
      },
      rowSpan(key, parent) {
        let list = [];
        let position = 0;
        this.tableData.forEach((item, index) => {
          if (index === 0) {
            list.push(1);
            position = 0;
          } else {
            if ( this.tableData[index][key] ===  this.tableData[index - 1][key]) {
              if (parent && parent[index] !== 0) {
                list.push(1);
                position = index;
              } else {
                list[position] += 1;
                list.push(0);
              }
            } else {
              list.push(1);
              position = index;
            }
          }
        });
        return list;
      },
      spanMethod({row, column, rowIndex, columnIndex}) {

        for (let i = 0; i < this.spanArr.length; i++) {
          const ele = this.spanArr[i];
          if (column.property === ele.prop) {
            const _row = ele.span[rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return { rowspan: _row, colspan: _col };
          }
        }
      }


    }
  };
</script>
<style lang="scss">

</style>
